from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from book.models import BookInfo, PeopleInfo
import re

# Create your views here.
from django.views import View


def create_book(request):
    book = BookInfo.objects.create(
        name='aaa',
        pub_date='2000-01-01',
        readcount=10,
    )

    return HttpResponse("create")


#################查询地址##############
def shop(request, city_id, shop_id):
    # request.GET
    # if not re.match('\d{5}',shop_id):
    #     return HttpResponse("没有此商品")
    print(shop_id)
    return HttpResponse("小饭店")


##############查询字符串#################
'''
 http://ip:port/path/path/?key=value&key1=value1
 url以?分割
 前：请求路径
 后：查询字符串 类似于字典 key=value 多个字符串用&拼接
'''


#
# def gou(request, iid):
#     query_params = request.GET
#     order = query_params.get('order')
#     print(order)
#     return HttpResponse("优书" + iid + order)

###############################
def register(request):
    data = request.POST
    print(data)  # <QueryDict: {'username': ['it'], 'password': ['123']}>
    return HttpResponse("OK")


############接收json##############
import json


def Json(request):
    # request.POST 无法接收JSON
    # body = request.body
    # body_str = body.decode()
    # print(type(body_str))
    # # <class 'str'> str形式的字符串
    # # JSON形式的字符串可以转变为字典
    # print(json.loads(body_str))
    print(request.META['SERVER_PORT'])
    return HttpResponse('json')


def method(request):
    print(request.method)
    return HttpResponse("method")


def response(request):
    # return HttpResponse("re", status=666)
    # 不能随便给状态码
    # resq = HttpResponse("re", status=200)
    # resq['name'] = 'cc'
    # return resq
    ###########JSONresponse##############
    info = {
        'name': 'it',
        'address': "秦皇岛",
    }
    girl_firends = [
        {'name': 'rose',
         'address': '北京'
         },
        {
            'name': 'joke',
            'address': '天津',
        }
    ]
    # data 返回的响应数据，一般为字典类型

    '''
        safe=True 表示数据(data)是字典数据
        JsonResponse 可以把字典转换为JSON 
    '''
    return JsonResponse(data=girl_firends, safe=False)


'''
 http://127.0.0.1:8000/set_cookie?username=it&password=123
'''


def set_cookie(request):
    # 1. 获取查询字符串数据
    username = request.GET.get('username')
    # 2. 服务器设置cookie信息
    response = HttpResponse("set cookie")
    response.set_cookie('name', username, max_age=3000)
    response.delete_cookie('name')
    response.delete_cookie('itcast2')
    return


def get_cookie(request):
    # 获取cookie
    # request.COOKIES 字典数据
    us = request.COOKIES.get('name')
    return HttpResponse(us)


###############################
# 1. session是保存在服务器端的数据----相对安全
# 2·. session需要依赖于cookie
'''
 第一次请求 http://127.0.0.1:8000/set_session/?username=it 我们在服务器设置session信息
 服务器同时会生成一个sessionid的cookie信息
 浏览器接收这个信息后，会把cookie数据保存起来
 
 之后的请求都会携带这个sessionid 服务器会验证这个sessionid 读取相关数据实现业务逻辑
'''


def set_session(request):
    # 1. 模拟获取用户信息
    # 2. 设置session信息
    # 3. 我们通过模型查询用户信息
    user_id = 1
    request.session['user_id'] = user_id
    request.session['username'] = request.GET.get('username')

    return HttpResponse("set_session")


def get_session(request):
    user_id = request.session.get('user_id')
    username = request.session.get('username')
    content = '{}, {}'.format(user_id, username)
    return HttpResponse(content)


####################类视图###################
def login(request):
    print(request.method)
    return HttpResponse("login")


class LoginView(View):
    def get(self, request):
        return HttpResponse("get get get")

    def post(self, request):  # post必须以/结尾
        return HttpResponse("post post post")


################################################
'''
我的订单、个人中心页面
如果登录用户可以访问
如果未登录用户，不应该访问，应该跳转到登录页面
定义一个订单、个人中心 类视图
'''
# 判断只有登录用户才可以访问页面
from django.contrib.auth.mixins import LoginRequiredMixin


class OrderView(LoginRequiredMixin,View ):

    def get(self, request):
        # islogin = True
        # if not islogin:
        #     return HttpResponse("你没有登录，跳转到整理页面中~~~~")
        return HttpResponse("get 我的订单页面")

    def post(self, request):
        return HttpResponse("post 我的订单页面")


